package com.sdkj.controller.personnel.employee;

import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.sdkj.base.common.FileUpload;
import com.sdkj.controller.base.BaseController;
import com.sdkj.entity.Department;
import com.sdkj.entity.Page;
import com.sdkj.entity.User;
import com.sdkj.util.AppUtil;
import com.sdkj.util.DateUtil;
import com.sdkj.util.ObjectExcelView;
import com.sdkj.util.Const;
import com.sdkj.util.PageData;
import com.sdkj.util.PathUtil;
import com.sdkj.util.Tools;
import com.sdkj.util.Jurisdiction;
import com.sdkj.service.personnel.employee.BaseService;
import com.sdkj.service.personnel.employee.RelationshipService;
import com.sdkj.service.personnel.employee.WorkService;
import com.sdkj.service.platform.DepartmentService;

/** 
 * 类名称：PersonnelEmployeeController
 * 创建人：sdkj 
 * 创建时间：2017-06-19
 */
@Controller
@RequestMapping(value="/employee")
public class EmployeeController extends BaseController {
	
	String menuUrl = "employee/list.do"; //菜单地址(权限用)
	@Resource(name="baseService")
	private BaseService baseService;
	
	@Resource(name="relationshipService")
	private RelationshipService relationshipService;
	
	@Resource(name="workService")
	private WorkService workService;
	
	@Resource(name="departmentService")
	private DepartmentService departmentService;
	
	/**
	 * 新增
	 */
	@RequestMapping(value="/save")
	public void save(HttpServletResponse response) throws Exception{
		logBefore(logger, "新增员工...");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {
			return;
		} // 校验权限
		String createtime=Tools.date2Str(new Date());
		PageData pd = new PageData();
		pd=this.getPageData();
		String base_id=this.get32UUID();
		String base_phone=pd.getString("base_phone");
		PageData pd4= new PageData();
		pd4=baseService.findEmployeeByPhone(base_phone);
		User user=baseService.findUserByPhone(base_phone);
		
		JSONObject arr = new JSONObject();
		if(user!=null && pd4==null){
			String USER_ID=user.getUSER_ID();
			pd.put("base_id",base_id);	//主键1
			pd.put("base_record_status", 0);
			pd.put("base_createtime",createtime);
			pd.put("base_updatetime",createtime);
		//	pd.put("company_id", getCurrentUser().getCompany().getCompanyId());
			pd.put("user_id", USER_ID);
			
			PageData pd1 = new PageData();
			pd1=this.getPageData();
			pd1.put("relation_id", this.get32UUID());	//主键2
			pd1.put("base_id", base_id);	//外键1
			pd1.put("relation_createtime",createtime);
			pd1.put("relation_updatetime",createtime);
			
			PageData pd2 = new PageData();
			pd2=this.getPageData();
			pd2.put("work_id", this.get32UUID());	//主键3
			pd2.put("base_id", base_id);	//外键1
			pd2.put("work_createtime", createtime);
			pd2.put("work_updatetime", createtime);
			
			baseService.save(pd);
			relationshipService.save(pd1);
			workService.save(pd2);
			arr.put("status", true);
			arr.put("msg","");
		}else{
			arr.put("status", false);
			arr.put("msg","手机号不存在或员工已存在！");
		}
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		String json = arr.toString();
		out.write(json);
		out.flush();
		out.close();
	}
	
	/**
	 * 删除
	 */
	@RequestMapping(value="/delete")
	public void delete(PrintWriter out){
		logBefore(logger, "删除员工...");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){return;} //校验权限
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			baseService.delete(pd);
			relationshipService.delete(pd);
			workService.delete(pd);
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	/**
	 * 员工离职
	 */
	@RequestMapping(value="/updateWorkStatus")
	public void updateWorkStatus(PrintWriter out){
		logBefore(logger, "员工离职...");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")){return;} //校验权限
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			pd.put("work_status", "4");
			workService.updateWorkStatus(pd);
			out.write("success");
			out.close();
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		
	}
	
	/**
	 * 归档页面
	 */
	@RequestMapping(value="/goUpdateRecord")
	public ModelAndView goUpdateRecord(){
		logBefore(logger, "员工档案归档页面...");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			pd = baseService.findById(pd);	//根据ID读取
			mv.setViewName("personnel/employee/employee_updateRecord");
			mv.addObject("msg", "updateRecord");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}
	
	/**
	 * 归档
	 */
	@RequestMapping(value="/updateRecord")
	public ModelAndView updateRecord() throws Exception{
		logBefore(logger, "归档...");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")){return null;} //校验权限
		PageData pd = new PageData();
		pd=this.getPageData();
		ModelAndView mv = this.getModelAndView();
		String updatetime=Tools.date2Str(new Date());
		pd.put("base_record_status", 1);
		pd.put("base_record_operatorid", getCurrentUser().getUSER_ID());
		pd.put("base_updatetime", updatetime);
		baseService.updateRecord(pd);
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 修改
	 */
	@RequestMapping(value="/edit")
	public ModelAndView edit(MultipartFile base_photo,HttpServletRequest request) throws Exception{
		logBefore(logger, "修改员工信息...");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")){return null;} //校验权限
		String filePath = null;
		String fileName=null;
		String fileNewPath = null;
		PageData pd = new PageData(request);
		if (null != base_photo && !base_photo.isEmpty()) {
//			filePath =PathUtil.getClasspath()+Const.EMPLOYEE;
//			fileNewPath = Const.EMPLOYEE;
			fileName = FileUpload.fileUpload(base_photo, filePath, request.getParameter("base_id")+System.currentTimeMillis());	
			pd.put("base_photo", fileNewPath+fileName);
		}else {
			System.out.println("上传失败");
		}
		ModelAndView mv = this.getModelAndView();
	
		String updatetime=Tools.date2Str(new Date());
		pd.put("base_record_status", 0);
		pd.put("base_updatetime", updatetime);
		pd.put("relation_updatetime", updatetime);
		pd.put("work_updatetime", updatetime);
		baseService.edit(pd);
		relationshipService.edit(pd);
		workService.edit(pd);
		mv.addObject("msg","success");
		mv.setViewName("save_result");
		return mv;
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list")
	public ModelAndView list(Page page){
		logBefore(logger, "人员信息列表...");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {
			return null;
		} // 校验权限
		int rank = 0;// 查看级别
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_zj")) {
			rank=0;
		}
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_dept")) {
			rank=1;
		}
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_company")) {
			rank=2;
		}
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		try{
			pd = this.getPageData();
			User user=getCurrentUser();
			pd.put("userId", user.getUSER_ID());
			pd.put("rank", rank);
//			pd.put("deptId", user.getDepartment().getDepartmentId());
//			pd.put("companyId", user.getCompany().getCompanyId());
			page.setPd(pd);
			List<PageData>	varList = baseService.list(page);	//列出PersonnelEmployee列表
			//列出所有部门
			List<Department> deptList = departmentService.listAllDepartment();

			mv.setViewName("personnel/employee/employee_list");
			mv.addObject("deptList", deptList);
			mv.addObject("varList", varList);
			mv.addObject("pd", pd);
			mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/**
	 * 去新增页面
	 */
	@RequestMapping(value="/goAdd")
	public ModelAndView goAdd(){
		logBefore(logger, "去新增员工页面...");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			List<Department> deptList = departmentService.listAllDepartment();
			mv.setViewName("personnel/employee/employee_add");
			mv.addObject("msg", "save");
			mv.addObject("pd", pd);
			mv.addObject("deptList", deptList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 去修改页面
	 */
	@RequestMapping(value="/goEdit")
	public ModelAndView goEdit(){
		logBefore(logger, "去修改人事信息页面...");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {
			return null;
		} // 校验权限
		int rank = 0;// 查看级别
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_zj")) {
			rank=0;
		}
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_dept")) {
			rank=1;
		}
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_company")) {
			rank=2;
		}
		System.out.println("rank:::"+rank);
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			List<Department> deptList = departmentService.listAllDepartment();
			pd = baseService.findById(pd);	//根据ID读取
			pd.put("rank", rank);
			mv.setViewName("personnel/employee/employee_edit");
			mv.addObject("msg", "edit");
			mv.addObject("pd", pd);
			mv.addObject("deptList", deptList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/**
	 * 批量删除
	 */
	@RequestMapping(value="/deleteAll")
	@ResponseBody
	public Object deleteAll() {
		logBefore(logger, "批量删除PersonnelEmployee");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "dell")){return null;} //校验权限
		PageData pd = new PageData();		
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			pd = this.getPageData();
			List<PageData> pdList = new ArrayList<PageData>();
			String DATA_IDS = pd.getString("DATA_IDS");
			if(null != DATA_IDS && !"".equals(DATA_IDS)){
				String ArrayDATA_IDS[] = DATA_IDS.split(",");
				baseService.deleteAll(ArrayDATA_IDS);
				pd.put("msg", "ok");
			}else{
				pd.put("msg", "no");
			}
			pdList.add(pd);
			map.put("list", pdList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		} finally {
			logAfter(logger);
		}
		return AppUtil.returnObject(pd, map);
	}
	
	/**
	 * 去详情页面
	 */
	@RequestMapping(value="/goDetail")
	public ModelAndView goDetail(){
		logBefore(logger, "去员工信息详情页...");
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {
			return null;
		} // 校验权限
		int rank = 0;// 查看级别
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_zj")) {
			rank=0;
		}
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_dept")) {
			rank=1;
		}
		if (Jurisdiction.buttonJurisdiction(menuUrl, "cha_company")) {
			rank=2;
		}
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			List<Department> deptList = departmentService.listAllDepartment();
			pd = baseService.findById(pd);	//根据ID读取
			pd.put("rank", rank);
			mv.setViewName("personnel/employee/employee_detail");
			mv.addObject("pd", pd);
			mv.addObject("deptList", deptList);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}						
		return mv;
	}	
	
	/*
	 * 导出到excel
	 * @return
	 */
	@RequestMapping(value="/excel")
	public ModelAndView exportExcel(){
		logBefore(logger, "导出PersonnelEmployee到excel");
		if(!Jurisdiction.buttonJurisdiction(menuUrl, "sdkja")){return null;}
		ModelAndView mv = new ModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			Map<String,Object> dataMap = new HashMap<String,Object>();
			List<String> titles = new ArrayList<String>();
			titles.add("");	//1
			titles.add("");	//2
			titles.add("");	//3
			titles.add("");	//4
			titles.add("");	//5
			titles.add("");	//6
			titles.add("");	//7
			titles.add("");	//8
			titles.add("");	//9
			titles.add("");	//10
			titles.add("");	//11
			titles.add("");	//12
			titles.add("");	//13
			titles.add("");	//14
			titles.add("");	//15
			titles.add("");	//16
			titles.add("");	//17
			titles.add("");	//18
			titles.add("");	//19
			titles.add("");	//20
			titles.add("");	//21
			titles.add("");	//22
			titles.add("");	//23
			titles.add("");	//24
			dataMap.put("titles", titles);
			List<PageData> varOList = baseService.listAll(pd);
			List<PageData> varList = new ArrayList<PageData>();
			for(int i=0;i<varOList.size();i++){
				PageData vpd = new PageData();
				vpd.put("var1", varOList.get(i).getString("base_id"));	//1
				vpd.put("var2", varOList.get(i).getString("base_name"));	//2
				vpd.put("var3", varOList.get(i).getString("base_sex"));	//3
				vpd.put("var4", varOList.get(i).getString("base_identity"));	//4
				vpd.put("var5", varOList.get(i).getString("base_birthday"));	//5
				vpd.put("var6", varOList.get(i).getString("base_nationality"));	//6
				vpd.put("var7", varOList.get(i).getString("base_native_place"));	//7
				vpd.put("var8", varOList.get(i).getString("base_politics"));	//8
				vpd.put("var9", varOList.get(i).getString("base_phone"));	//9
				vpd.put("var10", varOList.get(i).getString("base_marriage"));	//10
				vpd.put("var11", varOList.get(i).getString("base_record_number"));	//11
				vpd.put("var12", varOList.get(i).getString("base_record_position"));	//12
				vpd.put("var13", varOList.get(i).getString("base_email"));	//13
				vpd.put("var14", varOList.get(i).getString("base_address"));	//14
				vpd.put("var15", varOList.get(i).getString("base_education_background"));	//15
				vpd.put("var16", varOList.get(i).getString("base_graduation"));	//16
				vpd.put("var17", varOList.get(i).getString("base_major"));	//17
				vpd.put("var18", varOList.get(i).getString("base_employee_type"));	//18
				vpd.put("var19", varOList.get(i).getString("base_photo"));	//19
				vpd.put("var20", varOList.get(i).getString("user_id"));	//20
				vpd.put("var21", varOList.get(i).getString("company_id"));	//21
				vpd.put("var22", varOList.get(i).getString("filiale_id"));	//22
				vpd.put("var23", varOList.get(i).getString("base_createtime"));	//23
				vpd.put("var24", varOList.get(i).getString("base_updatetime"));	//24
				varList.add(vpd);
			}
			dataMap.put("varList", varList);
			ObjectExcelView erv = new ObjectExcelView();
			mv = new ModelAndView(erv,dataMap);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
	}
	
	/* ===============================权限================================== */
	public Map<String, String> getHC(){
		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
		Session session = currentUser.getSession();
		return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
	}
	/* ===============================权限================================== */
	
	@InitBinder
	public void initBinder(WebDataBinder binder){
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
	}
}
